/**
 * Created by sky on 2019/3/18.
 */
layui.define(function (exports) {
    function CommonHttp() {
        var self = this;
        self.createRequest();
        self.timeout = 8000;
    }

    CommonHttp.prototype.getJSON = function (url, urlBackup, api, type, data, succCallBack, errCallBack, showLoading, option, isIgnoreTokenError) {
        var self = this;
        if (showLoading) {
            console.log("toast:加载中...");
        }
        if (self.httpRequest) {
            //创建http请求
            //self._createRequest();
            //open连接
            var sendData = self.getSendData(option, data);
            var fullUrl = self.getFullUrl(url, api, type, sendData);
            self.httpRequest.open(type, fullUrl, true);
            //发送请求
            self.setHeader();
            self.sendRequest(type, option, sendData);
            //响应请求
            var response = function () {
                self.onResponse(succCallBack, errCallBack, isIgnoreTokenError);
            };
            self.httpRequest.onreadystatechange = response;
            self.onTimeout(errCallBack);
        }
    };

    CommonHttp.prototype.createRequest = function () {
        var self = this;
        var httpRequest = new XMLHttpRequest();
        if (null == httpRequest) {
            console.log("toast:请求初始化失败");
        } else {
            self.httpRequest = httpRequest;
        }
    };

    CommonHttp.prototype.getSendData = function (option, data) {
        var sendData = '';
        if (option.json) {
            //发送完整的json数据, 如 {"type":1001}:
            sendData = data;
        } else {
            //直接发送字符串式的数据, 如 bet_term=1&amount=5
            for (var i in data) {
                if (sendData != '') {
                    sendData += "&";
                }
                sendData += (i + "=" + data[i]);
            }
        }
        return sendData;
    };

    CommonHttp.prototype.getFullUrl = function (url, api, type, sendData) {
        if (url) {
            var prefixIndex = url.indexOf('http');
            if (prefixIndex < 0) {
                url = 'http://' + url;
            }
            //如果url是以反斜杠结尾，将其去掉
            if (url.charAt(url.length - 1) == "/") {
                url = url.substring(0, url.length - 1);
            }
        }
        //如果api不是以反斜杠打头，将其补上
        if (api.charAt(0) != "/") {
            api = "/" + api;
        }
        var fullUrl = url + api;
        var timestamp = new Date().getTime();
        var tParams = "&qt_utc=" + timestamp;
        var pInfo = '';
        if (type.toUpperCase() == "POST" || type.toUpperCase() == "PUT") {
            if (fullUrl.indexOf("?") >= 0) {
                fullUrl = fullUrl + '&p=' + pInfo;
            } else {
                fullUrl = fullUrl + '?p=' + pInfo;
            }
            fullUrl += tParams;
            console.log('CommonHttp post url:' + fullUrl);
        } else {
            if (sendData && sendData != '') {
                fullUrl += '?';
                fullUrl += sendData;
                fullUrl += '&p=';
            } else {
                fullUrl += '?p=';
            }
            fullUrl += pInfo;
            fullUrl += tParams;
            console.log('CommonHttp get url:' + fullUrl);
        }
        return fullUrl;
    };

    CommonHttp.prototype.setHeader = function () {
        var self = this;
        if (self.httpRequest) {
            self.httpRequest.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            var uid = "";
            var token = "";
            if (uid && token) {
                self.httpRequest.setRequestHeader('X-AUTH-USER', uid.toString());
                self.httpRequest.setRequestHeader('X-AUTH-TOKEN', token.toString());
            }
        }
    };

    CommonHttp.prototype.sendRequest = function (type, option, sendData) {
        var self = this;
        if (self.httpRequest) {
            if (type.toUpperCase() == "POST" || type.toUpperCase() == "PUT") {
                if (option && option.json) {
                    //发送完整的json数据, 如 {"type":1001}:
                    self.httpRequest.send(JSON.stringify(sendData));
                } else {
                    //直接发送字符串式的数据, 如 bet_term=1&amount=5
                    self.httpRequest.send(sendData);
                }
            } else {
                self.httpRequest.send();
            }
        }
    };

    CommonHttp.prototype.onResponse = function (succCallBack, errCallBack, isIgnoreTokenError) {
        var self = this;
        var _errFun = function (responseJson, errCallBack, isIgnoreTokenError) {
            if (typeof (errCallBack) == "function") {
                errCallBack(responseJson);
            }
        };

        var fun = function () {
            var requestState = self.httpRequest.readyState; //请求状态(1,2,3,4)
            var httpStatus = self.httpRequest.status; //http状态码(200,非200)
            if (requestState == 4) { //请求完成
                console.log("remove toast:加载中...");
                if (self.timer) {
                    clearTimeout(self.timer);
                }
                var responseText = null;
                if (self.httpRequest) {
                    responseText = self.httpRequest.responseText;
                }
                if (responseText && responseText != "") {
                    if (responseText.indexOf('<!DOCTYPE html>') >= 0) {
                        responseText = '{}';
                    }
                    if (responseText.indexOf('<') == 0) {
                        responseText = '{}';
                    }

                    var responseJson = JSON.parse(responseText);
                    var jsonData = responseJson.data;
                    var jsonStatus = responseJson.status;
                    if (httpStatus == 200 && jsonStatus == 0) {
                        if (jsonData) {
                            if (typeof (succCallBack) == "function") {
                                succCallBack(jsonData);
                            }
                        }
                    } else {
                        if (httpStatus) {
                            _errFun(responseJson, errCallBack, isIgnoreTokenError);
                        }
                    }
                } else {
                    _errFun();
                    console.log("toast:请求超时");
                }
            } else {
                //console.log("http request......" + requestState);
            }
        };
        fun();
    };

    CommonHttp.prototype.onTimeout = function (errCallBack) {
        var self = this;
        self.onTimeout = function () {
            console.log("remove toast:加载中...");
            if (typeof (errCallBack) == "function") {
                console.log("timeOut callback");
                errCallBack(-1); //-1用来兼容之前的api的errCallBack
            }
            console.log("toast:请求超时");
        };
        self.timer = setTimeout(self.onTimeout, self.timeout);
    };


    exports('CommonHttp', {});
});
